import React, { useEffect, useRef, useState, useMemo, useContext } from 'react';
import { SchemaManage } from '@/components/SchemaComponent';
import { connect } from 'umi';
import { MaterialAndAssetControllerAPI } from '../common/type';
import { getTableColumns } from '../mconfig';
import { assetListManageServices } from '../services';
import { history } from 'umi';
import { CloudDownloadOutlined } from '@ant-design/icons';
import { ExportModal } from './ExportModal';

const MaterialAndAssetControllerView: React.FC<MaterialAndAssetControllerAPI.IMaterialManageView> = ({ curRes }) => {
  /** 是否展示导出弹窗 */
  const [isShowExportModal, setIsShowExportModal] = useState<Record<string, any>>({});
  /** 表格选中内容 */
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  /** 表格选中record */
  const [selectRows, setSelectRows] = useState<Record<string, any>[]>([]);

  /** 管理页services */
  const { getAssetListTableData, data, loading, pagination, searchList, searchParams } = assetListManageServices(curRes);

  /** 管理页的ref */
  const MaterialManageViewRef: any = useRef();

  /** 切换头部方法 */
  const onSwitch = (key: string | undefined | number, searchValues: any, params: any) => {
    getAssetListTableData({ ...params, ...searchValues });
  };

  /** 重置方法 */
  const onReset = (otherParams: MaterialAndAssetControllerAPI.IAssetTableRequestType) => {
    getAssetListTableData({ ...otherParams });
  };

  /** 搜索方法 */
  const onSearch = (otherParams: MaterialAndAssetControllerAPI.IAssetTableRequestType) => {
    getAssetListTableData({ ...otherParams });
  };

  /** 表格刷新数据 */
  const reloadTableData = () => {
    getAssetListTableData({});
  };

  /** 分页方法 */
  const onPageChange = (current: any, pageSize: any, params: any) => {
    getAssetListTableData({ pageSize, current, ...params });
  };

  /** Table的columns集合 */
  const columns: Record<string, any>[] = useMemo(() => {
    return getTableColumns(curRes);
  }, [curRes]);

  /** 新增操作按钮 */
  const actionList: MaterialAndAssetControllerAPI.IActionList = useMemo(() => {
    return [
      {
        title: '导出',
        visible: curRes?.['/assetMaterial/queryExport'],
        type: 'primary',
        icon: <CloudDownloadOutlined />,
        onClick: () => {
          setIsShowExportModal({ isShow: true });
        },
      },
    ];
  }, [curRes]);

  useEffect(() => {
    if (history.location.pathname == '/materialAndAssetController/manage') {
      reloadTableData();
    }
  }, [history.location.pathname]);

  return (
    <>
      <div
        id={'custom-preview-container'}
        style={{
          position: 'relative',
          overflow: 'hidden',
          height: '100%',
          width: '100%',
        }}
      >
        <SchemaManage
          ref={MaterialManageViewRef}
          searchProps={{
            switchList: [], //头部切换列表
            searchList,
            onSwitch,
            onReset,
            onSearch,
          }}
          actionList={actionList} // 操作按钮
          // actionList={[]} // 操作按钮
          tableProps={{
            columns: columns,
            dataSource: data?.rows ? data.rows : [],
            rowKey: 'id',
            loading: loading,
            pagination: pagination as any,
            onPageChange: onPageChange,
            // rowSelection: curRes?.['/expertInfoController/export']
            rowSelection: false
              ? {
                  type: 'checkBox',
                  selectedRowKeys,
                  onSelect: (record: any, selected: any) => {
                    if (selected) {
                      setSelectedRowKeys([...selectedRowKeys, record?.id]);
                      setSelectRows([...selectRows, record]);
                    } else {
                      const rowsList = selectRows?.filter((item) => record?.id != item?.id);
                      setSelectedRowKeys(rowsList?.map((i: Record<string, any>) => i?.id));
                      setSelectRows(rowsList);
                    }
                  },
                  onSelectAll: (selected: any, _: any, changeRows: any) => {
                    let dataKeys: any[] = [];
                    data?.rows?.forEach((item: Record<string, any>) => {
                      dataKeys?.push(item?.id);
                    });
                    if (selected) {
                      let keylist = Array.from(new Set([...dataKeys, ...selectedRowKeys]));
                      setSelectedRowKeys(keylist);
                      setSelectRows([...selectRows, ...changeRows]);
                    } else {
                      let newarr: any[] = selectedRowKeys?.filter((item) => {
                        return !dataKeys?.includes(item);
                      });
                      setSelectedRowKeys(newarr);
                      let keys: any[] = [];
                      changeRows?.forEach((item: any) => {
                        keys?.push(item?.id);
                      });
                      const newRows = selectRows?.filter((item) => {
                        return keys?.indexOf(item?.id) == -1;
                      });
                      setSelectRows(newRows);
                    }
                  },
                }
              : undefined,
          }}
        />
      </div>
      {/* 导出弹窗 */}
      {isShowExportModal?.isShow && <ExportModal onClose={() => setIsShowExportModal({})} searchParams={searchParams} selectedRowKeys={selectedRowKeys} />}
    </>
  );
};

export default connect(({ baseLogin, navTab }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
  navTab,
}))(MaterialAndAssetControllerView);
